import json

from TestToolsV2.tools.Log import Log
from TestToolsV2.view.OpenDialog import openDialog

log = Log()


class readConfig:
    """
    将读取到的config文件内容转化为字典类型数据
    """

    def __init__(self, dataPath):
        self.__dataDict = {}
        self.__dataPath = dataPath
        self.openDialog = openDialog()
        self.__lod_json()

    def __lod_json(self):
        """
        读取文件数据（JSON格式）
        """
        if self.__dataPath:
            try:
                with open(self.__dataPath, "r", encoding="utf-8") as f:
                    content = f.read()
                    self.__dataDict = json.loads(content)
            except FileNotFoundError:
                self.openDialog.showMessage(f"readConfig => __lod_json: {self.__dataPath} 读取失败！")

    def __write_json(self):
        """
        将新数据覆盖源文件（JSON格式）
        """
        if self.__dataPath:
            try:
                with open(self.__dataPath, "w", encoding="utf-8") as f:
                    json_data = json.dumps(self.__dataDict, ensure_ascii=False)
                    f.write(json_data)
            except FileNotFoundError:
                self.openDialog.showMessage(f"readConfig => __lod_json: {self.__dataPath} 写入失败！")

    def get_forkey(self, key):
        """
        通过键获得对应的值,没有值则返回字符串"NULL"
        """
        value = "NULL"
        if key in self.__dataDict.keys():
            value = self.__dataDict[key]
        return value

    def set_key_value(self, key, value):
        """
        设置已有键的值，没有的不可设置
        """
        if key in self.__dataDict.keys():
            self.__dataDict[key] = value

    def set_all(self, _dict: dict):
        """
        将指定字典中的键值对的值写入 redeconfig 中，如果键不存在，不会写入
        """
        for key in _dict.keys():
            if key in self.__dataDict.keys():
                self.__dataDict[key] = _dict[key]

    def get_dataDict(self):
        """
        获取整个文件数据，仅获取数据，不获得对象
        """
        if self.__dataDict:
            return self.__dataDict.copy()
        else:
            return {}

    def write_dataDict(self, ):
        """
        将新数据覆盖源文件
        """
        self.__write_json()
